package com.hck.trigger.http;

import com.hck.api.model.*;
import com.hck.domain.user.service.IUserService;
import com.hck.types.model.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.util.StringUtils;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.annotation.Resource;
import com.hck.types.common.AliOssProperties;
import com.hck.types.common.AliOssUtil;
import org.springframework.beans.factory.annotation.Autowired;

@RestController
@RequestMapping("/api/user")
@Tag(name = "用户接口", description = "用户相关操作")
public class UserController {

    @Resource
    private IUserService userService;

    @Autowired
    private AliOssProperties aliOssProperties;

    @PostMapping("/register")
    @Operation(summary = "用户注册", description = "新用户注册")
    public Response<UserRegisterResponseDTO> register(@RequestBody UserRegisterRequestDTO requestDTO) {
        UserRegisterResponseDTO responseDTO = userService.register(requestDTO);

        if (responseDTO.getSuccess()) {
            return Response.<UserRegisterResponseDTO>builder()
                    .code("200")
                    .data(responseDTO)
                    .info("注册成功")
                    .build();
        }

        return Response.<UserRegisterResponseDTO>builder()
                    .code("400")
                    .data(responseDTO)
                    .info(responseDTO.getErrorMessage())
                    .build();

    }

    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "通过用户名和密码登录")
    public Response<UserLoginResponseDTO> login(@RequestBody UserLoginRequestDTO requestDTO) {
        UserLoginResponseDTO responseDTO = userService.login(requestDTO);

        if (responseDTO.getSuccess()) {
            return Response.<UserLoginResponseDTO>builder()
                    .code("200")
                    .data(responseDTO)
                    .info("登录成功")
                    .build();
        }

        return Response.<UserLoginResponseDTO>builder()
                    .code("400")
                    .data(responseDTO)
                    .info(responseDTO.getErrorMessage())
                    .build();

    }

    @GetMapping("/info/{userId}")
    @Operation(summary = "获取用户信息", description = "根据用户ID获取用户详细信息")
    public Response<UserInfoDTO> getUserInfo(@PathVariable Long userId) {
        UserInfoDTO userInfo = userService.getUserInfo(userId);
        
        if (userInfo != null) {
            return Response.<UserInfoDTO>builder()
                    .code("200")
                    .data(userInfo)
                    .info("获取成功")
                    .build();
        } else {
            return Response.<UserInfoDTO>builder()
                    .code("404")
                    .data(null)
                    .info("用户不存在")
                    .build();
        }
    }


    @PostMapping("/authentic")
    @Operation(summary = "用户密码认证",description = "修改个人信息的密码认证")
    public Response<Boolean> authentic(@RequestBody AuthenticateRequestDTO authenticateRequestDTO){
        boolean result =  userService.authentic(authenticateRequestDTO);
        if(result)
            return Response.<Boolean>builder()
                    .code("200")
                    .info("认证成功")
                    .data(true)
                    .build();


        return Response.<Boolean>builder()
                .code("400")
                .info("认证失败")
                .data(false)
                .build();
    }


    @PostMapping("/updatePassword")
    @Operation(summary = "个人密码修改",description = "密码修改")
    public Response<Boolean> updatePassword(@RequestBody UpdatePasswordRequestDTO requestDTO){
        boolean result = userService.updatePassword(requestDTO);
        if(result)
            return Response.<Boolean>builder()
                    .code("200")
                    .info("修改密码成功，请重新登录")
                    .data(true)
                    .build();


        return Response.<Boolean>builder()
                .code("400")
                .info("原密码错误，请重试")
                .data(false)
                .build();
    }

    @GetMapping("/query")
    @Operation(summary = "用户信息查询测试", description = "用于前端健康检查")
    public Response<String> queryUserInfo(@RequestParam(value = "req", required = false, defaultValue = "") String req) {
        String result = userService.queryUserInfo(req);
        return Response.<String>builder()
                .code("200")
                .data(result)
                .info("查询成功")
                .build();
    }

    @PostMapping("/updateProfile")
    @Operation(summary = "更新个人信息", description = "用户可编辑的个人信息修改")
    public Response<Boolean> updateProfile(@RequestBody UpdateProfileRequestDTO requestDTO) {
        boolean result = userService.updateProfile(requestDTO);
        if(result)
            return Response.<Boolean>builder().code("200").info("修改成功").data(true).build();
        return Response.<Boolean>builder().code("400").info("修改失败").data(false).build();
    }

    @PostMapping("/uploadAvatar")
    @Operation(summary = "上传头像", description = "上传用户头像图片，返回图片URL")
    public Response<String> uploadAvatar(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Response.<String>builder().code("400").info("文件为空").data(null).build();
        }
        
        // 检查文件类型
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            return Response.<String>builder().code("400").info("文件名不能为空").data(null).build();
        }
        
        String ext = StringUtils.getFilenameExtension(originalFilename);
        if (ext == null || (!ext.equalsIgnoreCase("jpg") && !ext.equalsIgnoreCase("jpeg") 
            && !ext.equalsIgnoreCase("png") && !ext.equalsIgnoreCase("gif"))) {
            return Response.<String>builder().code("400").info("只支持jpg、jpeg、png、gif格式的图片").data(null).build();
        }
        
        // 检查文件大小（限制为100MB）
        if (file.getSize() > 100 * 1024 * 1024) {
            return Response.<String>builder().code("400").info("文件大小不能超过100MB").data(null).build();
        }
        
        String newFileName = UUID.randomUUID().toString() + "." + ext;
        
        try {
            // 检查OSS配置
            if (aliOssProperties.getEndpoint() == null || aliOssProperties.getAccessKeyId() == null 
                || aliOssProperties.getAccessKeySecret() == null || aliOssProperties.getBucketName() == null) {
                // OSS配置不完整，使用本地存储
                return uploadToLocal(file, newFileName);
            }
            
            AliOssUtil ossUtil = new AliOssUtil(
                aliOssProperties.getEndpoint(),
                aliOssProperties.getAccessKeyId(),
                aliOssProperties.getAccessKeySecret(),
                aliOssProperties.getBucketName()
            );
            String url = ossUtil.upload(file.getBytes(), "avatar/" + newFileName);
            return Response.<String>builder().code("200").info("上传成功").data(url).build();
        } catch (Exception e) {
            e.printStackTrace();
            // OSS上传失败，尝试本地存储
            try {
                return uploadToLocal(file, newFileName);
            } catch (Exception localException) {
                return Response.<String>builder().code("500").info("上传失败: " + e.getMessage()).data(null).build();
            }
        }
    }
    
    /**
     * 本地文件上传
     */
    private Response<String> uploadToLocal(MultipartFile file, String fileName) throws IOException {
        // 创建上传目录
        String uploadDir = "uploads/avatar/";
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        
        // 保存文件
        File destFile = new File(uploadDir + fileName);
        file.transferTo(destFile);
        
        // 返回本地访问URL
        String url = "/uploads/avatar/" + fileName;
        return Response.<String>builder().code("200").info("上传成功").data(url).build();
    }
}